
<template>
    <div class="app-container" v-loading="loading">
        <div class="container" >
      <el-form ref="searchForm" :model="searchForm" inline>
        <el-form-item label="设备编号/资产编号:">
          <el-col :span="6">
            <el-input v-model="searchForm.text" clearable style="width:200px;"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="起止时间:">
          <el-date-picker v-model='searchForm.dateTime' type='datetimerange' :picker-options='pickerOptions'
            range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期' align='right' format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss" @change='changeTime' clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维度:">
          <el-select v-model="searchForm.dimension" filterable clearable placeholder="请选择">
            <el-option v-for="item in timeDimensionList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺:">
          <el-select v-model="searchForm.storeId" filterable clearable placeholder="请选择">
            <el-option v-for="item in storeList" :key="item.value" :label="item.value + '——' + item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
                <el-button
                    style="margin-left:5px;background:#5B6BF4;font-family:'HarmonyOS_Sans_SC_Regular';border:none"
                    type="primary" icon="el-icon-search" size="mini" @click="queryByForm">检索</el-button>
            </el-form-item>
        <!-- <el-form-item>
          <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="importAssetcode"
          >导入资产编号 (Excel)</el-button
          >
        </el-form-item> -->
  
        <el-form-item>
          <!-- <ExportExcel :list="exportList" :tHeader="tHeader" :tValue="tValue" filename="KPI-设备" buttonName="数据导出"></ExportExcel> -->
        </el-form-item>
  
  
  
  
  
  
  
  
      </el-form>
  
      <el-table ref="deviceTable" v-loading="loading" :data="devicesData" style="width: 100%"
        @selection-change="handleSelectionChange()" row-key="id">
        <el-table-column type="selection" width="55" :reserve-selection="true">
        </el-table-column>
        <el-table-column label="资产编号" prop="assetCode" align="center">
          <template slot-scope="scope">
            <el-popover placement="top" width="180" trigger="hover">
              <p>设备id ：{{ scope.row.deviceId }}</p>
              <p>设备名称：{{ scope.row.deviceName }}</p>
              <span slot="reference">{{ scope.row.assetCode || '暂未绑定' }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="通电" prop="power" align="center">
          <template slot-scope="scope">
            {{ scope.row.power === 0 ? '电池供电' : '市电供电' }}
          </template>
        </el-table-column>
        <el-table-column label="通电时长" prop="powerDuration" align="center"></el-table-column>
        <el-table-column label="有效开门数" prop="openDoorCount" align="center"></el-table-column>
        <el-table-column label="失联" prop="missing" align="center">
          <template slot-scope="scope">
            {{ scope.row.power === 0 ? '正常' : '失联' }}
          </template>
        </el-table-column>
        <el-table-column label="低功耗" prop="lowPower" align="center"></el-table-column>
        <el-table-column label="位置异常" prop="locationAbnormal" align="center">
          <template slot-scope="scope">
            {{ scope.row.locationAbnormal === 0 ? '正常' : '异常' }}
          </template>
        </el-table-column>
        <el-table-column label="温度异常" prop="tempAbnormal" align="center">
          <template slot-scope="scope">
            {{ scope.row.locationAbnormal === 0 ? '正常' : '异常' }}
          </template>
        </el-table-column>
        <el-table-column label="图片油污异常" prop="sieveAbnormal" align="center">
          <template slot-scope="scope">
            {{ scope.row.locationAbnormal === 0 ? '正常' : '异常' }}
          </template>
        </el-table-column>
        <el-table-column label="平均纯净度（空）" prop="purityEmptyAvg" align="center"></el-table-column>
        <el-table-column label="平均纯净度" prop="purityAvg" align="center"></el-table-column>
        <el-table-column label="国家" prop="country" align="center"></el-table-column>
        <el-table-column label="省" prop="province" align="center"></el-table-column>
        <el-table-column label="市" prop="city" align="center"></el-table-column>
        <el-table-column label="区" prop="district" align="center"></el-table-column>
        <el-table-column label="组织" prop="nickName" align="center">
          <template slot-scope="scope">
            {{ scope.row.user.nickname }}
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" prop="storeName" align="center"></el-table-column>
        <el-table-column label="店铺编码" prop="storeCode" align="center"></el-table-column>.
        <el-table-column label="日期" prop="date" align="center"></el-table-column>
  
  
      </el-table>
      <!-- <div class="page">
            <div style="margin-right: 20px;color: #333;font-family:'HarmonyOS_Sans_SC_Regular'">共7条</div>
            <el-button type="text" style="color:#333;margin-right: 10px;"><</el-button>
                    <div class="pageborder">1</div>
                    <el-button type="text" style="color:#333;margin-right: 10px;">></el-button>
                    <div style="margin-right: 10px;color: #333;font-family:'HarmonyOS_Sans_SC_Regular'">前往</div>
                    <el-input type="number" style="width: 60px;margin-right: 10px;" :min="0" v-model="pageIndex" />
                    <div style="color: #333;font-family:'HarmonyOS_Sans_SC_Regular'">页</div>
            </div> -->
      <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
        :page-sizes="[10, 20, 50, 100, 200, 500, 1000, 2000, 3000]" @pagination="pagination" />
    </div>
    </div>
  </template>
  
  <script>
  // import ExportExcel from '../../../components/ExcelUtils/Export2Excel.vue'
  // import { userListSon, userListPageAll } from '@/api/user'
  // import initCust from '@/plugins/mixin'
  // import { importAssetCode2 } from '@/api/device/masterDevice.js'
  // import { getKpiDevice } from '@/api/dataCenter/index.js'
  const emumStatus = {
    ONLINE: '在线',
    OFFLINE: '离线',
    UNACTIVE: '设备未激活',
    UNKNOWN: '未知',
    DISABLE: '已禁用',
  }
  export default {
    // mixins: [initCust],
    // components: {
    //   ExportExcel
    // },
    data() {
      return {
        devicesData: [],//表格数据
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        excelFile: '',
        importDialogOpen: false,
        importLoading: false,
        exportList: [],
        tHeader: ['冰柜资产码', '设备编号', '设备名称', '日期', '国家', '省', '市', '区', '组织', '店铺名称', '店铺编码', '通电', '失联', '低功耗', '位置异常', '温度异常', '图片异常', '通电时长', '有效开门数', '平均纯净度（含空位）', '平均纯净度（不含空位）'],
        tValue: ['assetCode', 'deviceId', 'deviceName', 'date', 'country', 'province', 'city', 'district', 'nickname', 'storeName', 'storeCode', 'power', 'missing', 'lowPower', 'locationAbnormal', 'tempAbnormal', 'sieveAbnormal', 'powerDuration', 'openDoorCount', 'purityEmptyAvg', 'purityAvg'],
        // oHeader: ['产品编号','cpuid','资产编号'],
        // oValue:['123','123','123'],
        // 店铺相关
        storeList: [],
        // 省市区相关
        province: '',
        city: '',
        region: '',
        provinceValue: '',
        cityValue: '',
        regionValue: '',
        provinceList: [],
        cityList: [],
        regionList: [],
        isQuery: true, // 判断是否是第一次渲染
        // 用户相关
        oneLevelUserInfoList: [],
        twoLevelUserInfoList: [],
        threeLevelUserInfoList: [],
        fourLevelUserInfoList: [],
        fiveLevelUserInfoList: [],
        sixLevelUserInfoList: [],
        paramId: '',
        showOneLevel: true,
        showTwoLevel: true,
        showThreeLevel: true,
        showFourLevel: true,
        showFiveLevel: true,
        showSixLevel: true,
  
        // 分页相关数据
        total: 0,
        pageNum: 1,
        pageSize: 20,
        timeDimensionList: [
          {
            value: 1,
            label: '日'
          },
          {
            value: 2,
            label: '周'
          },
          {
            value: 3,
            label: '月'
          },
          {
            value: 4,
            label: '季度'
          }
        ],
        loading: false,
        searchForm: {
          text: '',  //设备编号 或 资产编号
          storeId: '',  //店铺id
          dateTime: [],
          startDate: '',//开始日期,格式: 2023-02-20
          endDate: '', //结束日期,格式: 2023-02-20
          dimension: 1 // 时间维度（日/周/月/季度）日：1，周：2，月：3，季度:4
        },
        pageIndex:1,
      }
    },
    filters: {
      statusFilter(value) {
        return emumStatus[value] || '-'
      },
      filterDoorType(value) {
        console.log('@@ value ==>', value)
        const doorMap = {
          1: '左开门',
          2: '右开门',
          3: '双开门',
        }
        return doorMap[value]
      },
    },
    watch: {
      'addContainerForm.userId': function (val, old) {
        if (val === '') {
          this.addContainerForm.skuComposeId = ''
          return
        }
        this.getSkuComposeList()
        console.log('## value userId ==> ', val, this)
      },
    },
    created() {
      //this.handleQuery()
    },
    mounted() {
      
      
    },
    computed: {
  
    },
  
    methods: {
      /** 
       * 检索
       */
      handleQuery(isQuery) {
        //第一次使用不用出现提示，检索时需要出现提示
        if (isQuery) {
          if (this.searchForm.dateTime[0]) {
            this.searchForm.startDate = this.searchForm.dateTime[0].slice(0, 10)
          } else {
            this.$message.warning("请选择起止时间")
            return
          }
          if (this.searchForm.dateTime[1]) {
            this.searchForm.endDate = this.searchForm.dateTime[1].slice(0, 10)
          } else {
            this.$message.warning("请选择起止时间")
            return
          }
          if (!this.searchForm.dimension){
            this.$message.warning("请选择时间维度")
            return
          }
        } else {    
          let now = new Date();
          let year = now.getFullYear();
          let month = now.getMonth() + 1;
          let yesterday = now.getDate() - 1;
          let day = now.getDate();
          if (yesterday < 10) {
            yesterday = '0' + yesterday
          }
          if (day < 10) {
            day = '0' + day
          }
          if (month < 10) {
            month = '0' + month
          }
          this.searchForm.startDate = year + '-' + month + '-' + yesterday
          this.searchForm.endDate = year + '-' + month + '-' + day
          this.searchForm.dateTime.push(this.searchForm.startDate + ' 00:00:00')
      this.searchForm.dateTime.push(this.searchForm.endDate + ' 00:00:00')
         
          
        }
        console.log('## 时间为 ==>',this.searchForm.dateTime);
        this.loading = true
        const params = {
          text: this.searchForm.text,
          startDate: this.searchForm.startDate,
          endDate: this.searchForm.endDate,
          dimension: this.searchForm.dimension,
          storeId: this.searchForm.storeId
        }
        getKpiDevice(params).then((res) => {
          console.log(res)
          this.devicesData = res.data
        }).catch((err) => {
          this.$message.error(err.message)
        }).finally(() => {
          this.loading = false
          //this.total = res.total
        })
      },
  
      /**
       * 时间改变触发
       */
      changeTime() {
        console.log(this.searchForm.dateTime)
      },
      /**
       * 获取用户列表
       */
      getUserListInfo() {
        userListPageAll().then((res) => {
          if (res.code === 0 && res.data.length > 0) {
            this.oneLevelUserInfoList = res.data
            console.log("全部用户信息为", res)
          }
        })
      },
      handFileChange(e) {
        console.log(e)
        let fileData = e.target.files[0] //这是我们上传的文件
        this.excelFile = fileData
        console.log('@@ ee => ', this.excelFile)
      },
      submit() {
        if (this.excelFile) {
          console.log("传入的excel文件为", this.excelFile)
          const formData = new FormData()
          formData.append('file', this.excelFile)
          const param = {
            file: formData
          }
          importAssetCode2(param).then((res) => {
            if (res.code === 0) {
              this.$message.success("资产编码文件导入成功！")
              this.importDialogOpen = false
              this.handleQuery()
              this.excelFile = ''
            }
            console.log(res)
          }).catch((err) => {
            console.log(err)
            if (err.code === 1) {
              this.$message.error('执行失败，原因：' + err.message)
            } else if (err.code === 2) {
              this.$message.error('token错误，需要重新登陆。原因：' + err.message)
            } else if (err.code === -1) {
              this.$message.error('服务端错误，原因：' + err.message)
            }
          })
        } else {
          // this.$message.error('验证码错误')
          this.$message.error('请先上传文件')
        }
  
      },
      cancelImport() {
        this.importDialogOpen = false
        this.excelFile = ''
      },
      /** 导入资产编号 */
      importAssetcode() {
        this.importDialogOpen = true
      },
      //表格全选事件
      handleSelectionChange() {
        console.log("选中的数据", this.$refs.deviceTable.selection)
        this.exportList = this.$refs.deviceTable.selection
      },
      //搜索框用户选择改变
      selectChange(level) {
        if (level === 1) {
          this.searchForm.twoUserId = ''
          this.searchForm.threeUserId = ''
          this.searchForm.fourUserId = ''
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showTwoLevel = true
          this.showThreeLevel = true
          this.showFourLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.userId
          for (var i = 0; i < this.oneLevelUserInfoList.length; i++) {
            if (this.paramId === this.oneLevelUserInfoList[i].id) {
              if (this.oneLevelUserInfoList[i].subUsers.length > 0) {
                this.twoLevelUserInfoList = this.oneLevelUserInfoList[i].subUsers
                this.showTwoLevel = false
              }
            }
          }
        } else if (level === 2) {
          this.searchForm.threeUserId = ''
          this.searchForm.fourUserId = ''
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showThreeLevel = true
          this.showFourLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.twoUserId
          for (var i = 0; i < this.twoLevelUserInfoList.length; i++) {
            if (this.paramId === this.twoLevelUserInfoList[i].id) {
              if (this.twoLevelUserInfoList[i].subUsers.length > 0) {
                this.threeLevelUserInfoList = this.twoLevelUserInfoList[i].subUsers
                this.showThreeLevel = false
              }
            }
          }
        } else if (level === 3) {
          this.searchForm.fourUserId = ''
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showFourLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.threeUserId
          for (var i = 0; i < this.threeLevelUserInfoList.length; i++) {
            if (this.paramId === this.threeLevelUserInfoList[i].id) {
              if (this.threeLevelUserInfoList[i].subUsers.length > 0) {
                this.fourLevelUserInfoList = this.threeLevelUserInfoList[i].subUsers
                this.showFourLevel = false
              }
            }
          }
        } else if (level === 4) {
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.fourUserId
          for (var i = 0; i < this.fourLevelUserInfoList.length; i++) {
            if (this.paramId === this.fourLevelUserInfoList[i].id) {
              if (this.fourLevelUserInfoList[i].subUsers.length > 0) {
                this.fiveLevelUserInfoList = this.fourLevelUserInfoList[i].subUsers
                this.showFiveLevel = false
              }
            }
          }
        } else if (level === 5) {
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.paramId = this.searchForm.fiveUserId
          for (var i = 0; i < this.fiveLevelUserInfoList.length; i++) {
            if (this.paramId === this.fiveLevelUserInfoList[i].id) {
              if (this.fiveLevelUserInfoList[i].subUsers.length > 0) {
                this.sixLevelUserInfoList = this.fiveLevelUserInfoList[i].subUsers
                this.showSixLevel = false
              }
            }
          }
        } else {
          this.paramId = this.searchForm.sixUserId
        }
        userListSon({ userId: this.paramId }).then((res) => {
          if (res.data != '') {
            if (level === 1) {
              this.twoLevelUserListSearch = res.data
              this.showTwoLevel = false
            } else if (level === 2) {
              this.threeLevelUserListSearch = res.data
              this.showThreeLevel = false
            } else if (level === 3) {
              this.fourLevelUserListSearch = res.data
              this.showFourLevel = false
            } else if (level === 4) {
              this.fiveLevelUserListSearch = res.data
              this.showFiveLevel = false
            }
  
          }
        }).catch((err) => {
          console.log('## err ==> ', err)
        })
        //最后强制刷新
        this.$forceUpdate();
      },
      pagination() {
        // if (this.total > this.pageNum * this.pageSize) {
        //   this.pageNum += 1
        //   this.handleQuery()
        // }
        this.handleQuery()
      },
      queryByForm() {
        this.pageNum = 1;
        console.log("表单内容为", this.searchForm)
        this.handleQuery()
      },
    }
  }
  </script>
  
  <style lang="scss">
  .app-container {
    background-color: #F3F3F3;
    width: 100%;
    height: calc(100vh - 85px);
    display: flex;
    flex-direction: column;
    padding: 1%;
}
.container{
    background-color: white;
    height: 100%;
    padding: 15px;
    border-radius: 8px;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .radio {
    .el-radio__label {
      display: none;
    }
  }
  
  // ::v-deep .el-table .el-table__body td .cell:empty::after{
  //     content: "-";
  //   }
  .status-icon {
    width: 10px;
    height: 10px;
    display: inline-block;
    border-radius: 50%;
  }
  
  .c-grey {
    background: grey;
  }
  
  .c-green {
    background: green;
  }
  
  .c-red {
    background: red;
  }
  
  .c-yellow {
    background: yellow;
  }
  
  .device-long {
    white-space: nowrap;
  }
  
  .item-link {
    cursor: pointer;
    color: #409eff;
  }
  .page {
    display: flex;
    height: 80px;
    width: 100%;
    justify-content: center;
    align-items: center;
    box-shadow: 0px -2px 3px 0px rgba(0, 0, 0, 0.02);
    bottom: 10px;
    position: absolute;
}

.pageborder {
    margin-right: 10px;
    border: 1px solid #DCDFE6;
    width: 40px;
    height: 36px;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #333;
    font-family: 'HarmonyOS_Sans_SC_Regular'
}
::v-deep .el-form-item--medium .el-form-item__label {
    font-family: 'HarmonyOS_Sans_SC_Regular';
}
  </style>